First steps in ruby 2: Variables and chop
This builds on the pervious article here.
Last time we had a single loop that printed an increasing number of * characters. This time we’re going to add a loop (times do) that decreases the number of *s too. We’ll end up with pile of *s that looks like this:
$ ruby square.rb * ** *** **** ***** ***** **** *** ** *
Here’s the code:
thesize = 5 star_string = "*" thesize.times do puts star_string star_string = star_string + "*" end thesize.times do star_string = star_string.chop puts star_string end
This time we’ve added a variable, called “thesize”. In this case it’s just a number, we can change this to represent the size of the pile of characters. Once we’ve defined “thesize” at the top of the program we can use it wherever we want to. As you write larger program you’ll see why this is useful.
The first loop (times do) is the same as part 1, except we’re using “thesize” instead of 10. Check back and make sure you understand the difference.
The second loop does something a little different. It makes “star_string” shorter rather than longer. “star_string.chop” removes one character from the end of the string. So it chops characters off the string and prints them.
Homework
The homework is similar to the exercise in the previous part. Hopefully it’ll reaffirm the concepts of loops and variables.
1. Can you make the pile a little bigger or smaller? For example:
* ** *** **** ***** ****** ******* ****** ***** **** *** ** *
2. Like before, can you get it to print two little piles?
* ** *** **** **** *** ** * * ** *** **** **** *** ** *
3. Extra credit: Can you imagine how you’d get the program to print piles of varying sizes? What would you need to do?
* ** *** **** ***** ***** **** *** ** * * ** *** **** **** *** ** * * ** *** *** ** * * ** ** * * *